package com.dlc.felear.xiaoensale.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.TypeReference;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.DeviceInfo;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.entity.QueryMsgInfo;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.dlc.felear.xiaoensale.helper.SendData;
import com.itdlc.android.library.utils.APPDidUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;

public class UpdateMenuToDevicce {
    private static final String TAG = "UpdateMenuToDevicce";
    private static UpdateMenuToDevicce instance;
    private Context context;
    private int type;
    private List<DeviceInfo> data;
    private OperatorDao operatorDao;
    private ExecutorService executorService;

    public UpdateMenuToDevicce(Context context, int type) {
        this.context = context;
        this.type = type;
        data = new ArrayList<>();
        operatorDao = new OperatorDao(context);
        executorService = Executors.newCachedThreadPool();
        getDevices(11);
        getDevices(20);
    }

    public static UpdateMenuToDevicce getInstance(Context context, int type) {
        if (instance == null) {
            synchronized (UpdateMenuToDevicce.class) {
                if (instance == null) {
                    instance = new UpdateMenuToDevicce(context, type);
                }
            }
        }
        return instance;
    }

    public static UpdateMenuToDevicce getInstance() {
        return instance;
    }


    public void sendMenuInfo(final CookingMenu cookingMenu) {
        if (data.isEmpty()) {
            return;
        }
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                sendPct(cookingMenu);
//            }
//        });
    }

    /**
     * 发送菜谱到配菜台、炒菜机
     *
     * @param cookingMenu
     */
    private void sendPct(CookingMenu cookingMenu) {
        Log.e(TAG, "cookingMenu:" + JsonHelper.toJson(cookingMenu));
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", cookingMenu);
        map.put("option", type);
        Log.e(TAG, "paramer:" + JsonHelper.toJson(map));
        sendMsgToTarget(cookingMenu);
    }

    private void sendMsgToTarget(final CookingMenu cookingMenu) {
//    private void sendMsgToTarget(final Map<String, Object> map){
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    for (DeviceInfo deviceInfo : data) {
                        CookingMenu tempC = cookingMenu;
                        if (TextUtils.equals(deviceInfo.getDeviceId(), APPDidUtil.getAppDid())) {
                            continue;
                        }
                        if (!TextUtils.equals(deviceInfo.getDeviceId(), "666c55339cb712e178fdc722")) {
                            continue;
                        }
//                        sendOperators(operatorDao.queryForAllByMID(cookingMenu.getId()),
//                                cookingMenu.getId(), deviceInfo.getDeviceId());
                        if (deviceInfo.getType() == 20) {
                            if (TextUtils.equals(deviceInfo.getDeviceId(), "666c55339cb712e178fdc722")) {
                                sendOperators(operatorDao.queryForAllByMID(cookingMenu.getId()),
                                        cookingMenu.getId(), deviceInfo.getDeviceId());
                            }
                        }
                        HashMap<String, Object> map = new HashMap<>();
                        tempC.setOperators(null);
                        map.put("data", tempC);
                        map.put("option", deviceInfo.getType());
                        SendData.sendSocketInfo(map, deviceInfo.getDeviceId());
                        Thread.sleep(100);
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        });

    }

    private void sendOperators(final List<Operator> data, final String id, final String deviceId) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG, "paramer1:" + JsonHelper.toJson(data));
                if (data == null || data.isEmpty()) {
                    return;
                }
                try {
                    float div = 1000f;
                    String str = JsonHelper.toJson(data);
                    int size = (int) Math.ceil(str.length() / div);
                    int minDiv = (int) Math.ceil(data.size() / (float) size);
                    Log.e(TAG, "size:" + size + " length:" + str.length());
                    //长链接大小限制，需进行分包发送
                    for (int i = 0; i < size; i++) {
                        ArrayList<Operator> temArr = new ArrayList<>(minDiv);
                        for (int j = 0; j < minDiv; j++) {
                            int index = i * minDiv + j;
                            Log.e(TAG, "index=" + index);
                            if (index >= data.size()) {
                                break;
                            }
                            temArr.add(data.get(index));
                        }
                        HashMap<String, Object> map1 = new HashMap<>();
                        map1.put("id", id);
                        map1.put("index", i);
                        map1.put("size", data.size());
                        map1.put("operator", temArr);
                        sendOperator(map1, deviceId);
                        Thread.sleep(150);
//                Log.e(TAG, " length1:" + JsonHelper.toJson(temArr));
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        });
    }

    private void sendOperator(Map<String, Object> data, String deviceId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", data);
        map.put("option", 101);
        Log.e(TAG, "sendOperators:" + JsonHelper.toJson(map));
        SendData.sendSocketInfo(map, deviceId);
    }


    /**
     * 获取设备
     *
     * @param type
     */
    public void getDevices(int type) {
        HashMap<String, Object> params = new HashMap();
        params.put("deviceId", APPDidUtil.getAppDid());
        params.put("type", type);
        Log.e(TAG, "推送参数:" + JsonHelper.toJson(params));
        OkHttpManager.HttpPostJson(HttpApi.GETDEVICES, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "getDevices getDevices=" + e.getMessage());
            }

            @Override
            public void onResponse(String info, int i) {
                try {
                    Log.e(TAG, "getDevices onResponse=" + info);
                    QueryMsgInfo queryMsgInfo = JsonHelper.parserJson(info, new TypeReference<QueryMsgInfo<DeviceInfo>>() {
                    });
                    if (queryMsgInfo != null) {
                        if (queryMsgInfo.getData() != null && !queryMsgInfo.getData().isEmpty()) {
                            data.addAll(queryMsgInfo.getData());
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }
}
